package com.myk.game.lib.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 限流工具类，可用于防止短时间内重复执行同一任务
 * （暂未考虑多线程下情景）
 */
public class FastUtil {

    private static Map<String, Long> lastTimeMap = new HashMap<>();

    public static boolean isFast(String key, long interval) {
        if (lastTimeMap.get(key) == null) {
            lastTimeMap.put(key, 0L);
        }
        long time = System.currentTimeMillis();
        long timeD = time - lastTimeMap.get(key);
        if (0 < timeD && timeD < interval) {
            return true;
        }
        lastTimeMap.put(key, time);
        return false;
    }

    public static void isFast(String key, long interval, Runnable callback) {
        if (lastTimeMap.get(key) == null) {
            lastTimeMap.put(key, 0L);
        }
        long time = System.currentTimeMillis();
        long timeD = time - lastTimeMap.get(key);
        if (0 < timeD && timeD < interval) {
            callback.run();
        }
        lastTimeMap.put(key, time);
    }

    public static boolean isNotFast(String key, long interval) {
        return !isFast(key, interval);
    }

    public static void isNotFast(String key, long interval, Runnable callback) {
        if (!isFast(key, interval)) {
            callback.run();
        }
    }
}
